<template>
  <div class="favorites-container">
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>

    <div class="favorites-header">
      <h1 class="favorites-title">我的收藏</h1>
      <div class="favorites-summary">
        <span class="favorites-count">共 {{ favorites.length }} 件商品</span>
      </div>
    </div>

    <div class="favorites-content">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="error" class="error-state">
        <p>{{ error }}</p>
        <button @click="fetchFavorites" class="retry-btn">重试</button>
      </div>

      <div v-else-if="favorites.length === 0" class="empty-state">
        <img src="../assets/images/empty-favorites.svg" alt="空收藏夹" class="empty-img">
        <p class="empty-text">收藏夹还是空的</p>
        <router-link to="/" class="continue-shopping-btn">去购物</router-link>
      </div>

      <div v-else class="favorites-grid">
        <div v-for="item in favorites" :key="item.id" class="favorite-item">
          <div class="item-image" @click="router.push(`/product/${item.id}`)">
            <img :src="item.image" :alt="item.name">
            <button class="cancel-favorite-btn" @click.stop="handleCancelFavorite(item.id)">
              <i class="fas fa-heart"></i>
            </button>
          </div>
          <div class="item-info">
            <h3 class="item-name" @click="router.push(`/product/${item.id}`)">{{ item.name }}</h3>
            <p class="item-description">{{ item.description }}</p>
            <div class="item-price">￥{{ Number(item.price).toFixed(2) }}</div>
            <div class="item-stock">库存: {{ item.stock }}</div>
            <button class="add-to-cart-btn" @click="handleAddToCart(item)">加入购物车</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getFavoriteList, deleteFavorite } from '../../axios/favorite'
import { getProductDetail } from '../../axios/product'
import { addToCart } from '../../axios/cart'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const favorites = ref([])
const loading = ref(false)
const error = ref(null)

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  error.value = null
  try {
    const response = await getFavoriteList()
    console.log('收藏列表响应:', response)
    
    if (Array.isArray(response)) {
      // 直接使用后端返回的商品列表
      favorites.value = response.map(item => ({
        ...item,
        image: item.image || '../assets/images/default-product.svg'
      }))
    } else {
      error.value = '获取收藏列表失败'
      ElMessage.error('获取收藏列表失败')
    }
  } catch (err) {
    error.value = '获取收藏列表失败，请稍后重试'
    console.error('获取收藏列表失败:', err)
    ElMessage.error('获取收藏列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 取消收藏
const handleCancelFavorite = async (id) => {
  try {
    // 查找对应的收藏项
    const favoriteItem = favorites.value.find(item => item.id === id)
    if (!favoriteItem) {
      error.value = '找不到对应的收藏商品'
      return
    }
    
    const productId = id
    const response = await deleteFavorite(productId)
    console.log('取消收藏响应:', response)
    
    if (response.code === 1 || response === 1 || response === true) {
      // 取消收藏成功，从列表中移除
      ElMessage.success('取消收藏成功')
      favorites.value = favorites.value.filter(item => item.id !== id)
    } else {
      error.value = '取消收藏失败'
      ElMessage.error('取消收藏失败')
    }
  } catch (err) {
    error.value = '取消收藏失败，请稍后重试'
    console.error('取消收藏失败:', err)
    ElMessage.error('取消收藏失败，请稍后重试')
  }
}

// 加入购物车
const handleAddToCart = async (item) => {
  try {
    const response = await addToCart({
      productId: item.id,
      quantity: 1
    })
    if (response.code === 1) {
      ElMessage.success('已添加到购物车')
    } else {
      error.value = '添加到购物车失败'
      ElMessage.error('添加到购物车失败')
    }
  } catch (err) {
    error.value = '添加到购物车失败，请稍后重试'
    console.error('添加到购物车失败:', err)
    ElMessage.error('添加到购物车失败，请稍后重试')
  }
}

// 页面加载时获取收藏列表
onMounted(() => {
  fetchFavorites()
})
</script>

<style scoped>
.favorites-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 60px);
  position: relative;
}

.back-button {
  position: absolute;
  top: 10px;
  left: 30px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  color: #2c3e50;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 10;
}

.back-button:hover {
  transform: translateX(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  background: #f8f9fa;
}

.back-icon {
  font-size: 20px;
  font-weight: 500;
}

.back-text {
  font-weight: 500;
}

.favorites-header {
  margin-bottom: 30px;
  margin-top: 40px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.favorites-title {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 15px;
}

.favorites-summary {
  color: #666;
}

.favorites-content {
  min-height: 400px;
}

.loading-state,
.error-state,
.empty-state {
  text-align: center;
  padding: 40px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4CAF50;
  border-radius: 50%;
  margin: 0 auto 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 10px;
}

.empty-img {
  width: 200px;
  margin-bottom: 20px;
}

.empty-text {
  color: #666;
  margin-bottom: 20px;
}

.continue-shopping-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.favorite-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.favorite-item:hover {
  transform: translateY(-5px);
}

.item-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cancel-favorite-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.cancel-favorite-btn i {
  color: #e74c3c;
  font-size: 18px;
}

.cancel-favorite-btn:hover {
  background: white;
  transform: scale(1.1);
}

.item-info {
  padding: 15px;
}

.item-name {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 10px;
  font-weight: 600;
}

.item-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-price {
  color: #e74c3c;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.item-stock {
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
}

.add-to-cart-btn {
  width: 100%;
  padding: 10px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s;
}

.add-to-cart-btn:hover {
  background: #45a049;
}

@media (max-width: 768px) {
  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .item-image {
    height: 180px;
  }

  .item-name {
    font-size: 16px;
  }

  .item-price {
    font-size: 18px;
  }
}
</style> 